let addressStatus = false;
let settleStatus = false;

// 获取结算清单的商品
(function(){
	
	// 验证非法登录
	if(!localStorage.getItem('token')){
		alert('非法登录！');
		location.href = 'index.html';
		return;
	}
	
	// 获取元素
	let oOrderContent = document.querySelector('.order-content');
	
	// 请求数据
	lb.ajax({
		method: 'post',
		url: BASE_URL + '/api_settlement',
		data: {
			status : 'getsettlement',
			userId : localStorage.getItem('token'),
		},
		success(res){
			// console.log(res);
			if(res.code != 0){
				console.log(res);
				return;
			}
			
			// 组装Dom
			str = '';
			res.data.forEach(item => {
				str += `
					<div class="order-list">
						<div>
							<img src="${item.goods_thumb}" alt="" />
							<span>${item.goods_name}</span>
						</div>
						<div>
							<span>${item.goods_number}</span>
							<span>￥${item.price * item.goods_number}</span>
						</div>
					</div>
				`;
			})
			
			// 添加到页面
			oOrderContent.innerHTML = str;
			
		}
		
		
	})
	
})();

// 地址列表容器元素
let oAddressList = document.querySelector('.address-list');
// console.log(oAddressList);

// 新地址元素 -收货人姓名 -地址 -手机号 -保存地址 
let oConsigneeNameDom = document.querySelector('.consignee-name');
let oStreetDom = document.querySelector('.street');
let oTelDom = document.querySelector('.tel');
let oSaveBtn = document.querySelector('.save-btn');

// 获取省市区
let oProvinceDom = document.querySelector('.province');
let oCityDom = document.querySelector('.city');
let oTownDom = document.querySelector('.town');

let nowProvince = '';
let nowCity = '';
let nowTown = '';
let nowEditAddressId = '';
let lockAddress = false;

//默认调用一次获取地址
getAddressListData();

// 获取用户地址
function getAddressListData(){
	
	lb.ajax({
		method: 'post',
		url: BASE_URL + '/api_address',
		data: {
			status : 'getAddress',
			userId : localStorage.getItem('token')
		},
		success(res){
			console.log(res);
			if(res.code != 0){
				console.log(res);
				return;
			}
			
			// 验证是否有收获地址
			if(res.data.length == 0){
				oAddressList.innerHTML = '暂无地址，请添加收货地址！';
				return;
			}
			
			// 有收获地址 -> 调用渲染地址列表
			renderAddressList(res.data);
			addressStatus = true;
		},
	});
	
};

// 渲染地址列表的方法
function renderAddressList(data){
	
	// 整理数据结构 -展开数组 
	// 验证isDefault = true后将其设为第一个
	let newArr = [...data];
	newArr.forEach((item, index) => {
		if(item.isDefault == true){
			newArr.unshift(newArr.splice(index, 1)[0]);
		};
	});
	
	
	let str = '';
	newArr.forEach(item => {
		str += `
			<li class="list ${item.isActive ? 'isActive' : ''}"  address-id="${item.address_id}">
				<div>
					<p><span>${item.takename}</span><span>${item.tel}</span></p>
					<p>${item.province} ${item.city} ${item.district}</p>
					<p>${item.streetname}</p>
				</div>
				<div>
					<p class="set-default ${item.isDefault ? 'isDefault' : ''}" address-id="${item.address_id}">${item.isDefault ? '默认地址' : '设为默认'}</p>
					<p><span class="edit-address" address-id="${item.address_id}">编辑</span><span class="del-address" address-id="${item.address_id}">删除</span></p>
				</div>
			</li>
		`;
	});
	// 添加到页面
	oAddressList.innerHTML = str;
	// 开锁
	lockAddress = false;
	
	// 获取li标签和下面的结构 -设置默认地址 -编辑 -删除 
	// 获取到的都是数组形式 获取到的可能不止一个地址
	let aList = document.querySelectorAll('.address-list .list');
	let aSetDefault = document.querySelectorAll('.address-list .set-default');
	let aEditAddress = document.querySelectorAll('.address-list .edit-address');
	let aDelAddress = document.querySelectorAll('.address-list .del-address');
	
	// 遍历监听，点击设置为当前收货地址
	aList.forEach(item => {
		item.onclick = function(){
			// 后台设置
			lb.ajax({
				method: 'post',
				url: BASE_URL + '/api_address',
				data: {
					status : 'activeAddress',
					userId : localStorage.getItem('token'),
					addressId: this.getAttribute('address-id')
				},
				success: (res) => {
					// console.log(res);
					if(res.code != 0){
						console.log(res);
						return;
					}
					// 操作DOM元素
					aList.forEach(item => {
						// console.log(item.classList);
						item.classList.remove('isActive');
					});
					// console.log(this);
					this.classList.add('isActive');
				}
			});
			addressStatus = true;
		};
	});
	
	//批量监听 设置默认地址
	aSetDefault.forEach(item => {
		item.onclick = function(event){
			// 阻止冒泡
			event.stopPropagation();
			
			// 请求后台设置
			lb.ajax({
				method: 'post',
				url: BASE_URL + '/api_address',
				data: {
					status: 'defaultAddress',
					userId: localStorage.getItem('token'),
					addressId: this.getAttribute('address-id')
				},
				success: (res) => {
					// console.log(res);
					if(res.code != 0){
						console.log(res);
						return;
					};
					
					//操作DOM元素
					aSetDefault.forEach(item => {
						item.classList.remove('isDefault');
					});
					
					this.classList.add('isDefault');
					oAddressList.insertBefore(this.parentNode.parentNode, document.querySelectorAll('.address-list .list')[0]);
					
					getAddressListData();
				}
			});
		}
	});
		
	// 批量监听删除按钮
	aDelAddress.forEach(item => {
		item.onclick = function(){
			
			// 请求后台设置
			lb.ajax({
				method: 'post',
				url: BASE_URL + '/api_address',
				data: {
					status: 'deleteAddress',
					userId: localStorage.getItem('token'),
					addressId: this.getAttribute('address-id')
				},
				success: (res) => {
					console.log(res);
					if(res.code != 0){
						console.log(res);
						return;
					};
					
					//操作DOM元素
					this.parentNode.parentNode.parentNode.remove();
				}
			});
			
			// 重新渲染地址列表
			// getAddressListData();
		};
	});
		
	//批量监听编辑
	aEditAddress.forEach(item => {
		item.onclick = function(){
			// 设置要编辑的地址
			nowEditAddressId = this.getAttribute('address-id');
			// 数据设置到表单上去
			newArr.forEach(item => {
				if(item.address_id == nowEditAddressId){
					console.log(item);
					oConsigneeNameDom.value = item.takename;
					oStreetDom.value = item.streetname;
					oTelDom.value = item.tel;
				}
			});			
		};
		
	});
};


// 点击保存地址：保存新地址  和  编辑地址
oSaveBtn.onclick = function(){
	if(lockAddress) return;
	lockAddress = true;
	
	// 验证
	if(oConsigneeNameDom.value == ''){
		alert('姓名不能为空');
		return;
	};
	
	if(oStreetDom.value == ''){
		alert('详细地址不能为空');
		return;
	}
	
	
	let re = /^1[3456789]\d{9}$/g;
	if(!re.test(oTelDom.value)){
		alert('请输入正确的手机号');
		return;
	};
	
	// 验证是新增还是编辑 -不管是哪个都要先保存新地址，再删除旧地址
	lb.ajax({
		method: 'post',
		url: BASE_URL + '/api_address',
		data: {
			status: 'addAddress',
			userId: localStorage.getItem('token'),
			province: nowProvince,
			city: nowCity,
			district: nowTown,
			streetname: oStreetDom.value,
			takename: oConsigneeNameDom.value,
			tel: oTelDom.value,
		},
		success(res){
			console.log(res);
			if(res.code != 0){
				console.log(res);
				return;
			};
			
			// 验证
			if(nowEditAddressId){
				// 删除原来的地址
				lb.ajax({
					method: 'post',
					url: BASE_URL + '/api_address',
					data: {
						status: 'deleteAddress',
						userId: localStorage.getItem('token'),
						addressId: nowEditAddressId
					},
					success(res){
						if(res.code != 0){
							console.log(res);
							return;
						};
						
						// // 清空表单元素
						// 一定要把 nowEditAddressId 为空
						nowEditAddressId = '';
						// 多了一条数据，只要把它添加到渲染列表方法里面去
						getAddressListData();
					}
				})
			}else{
				// 多了一条数据，只要把它添加到渲染列表方法里面去
				getAddressListData();
				// 清空表单元素
			}
		}
	})
	
};

// 默认调用省
getProvince();

function getProvince(){
	lb.ajax({
		url: BASE_URL + '/api_country',
		data: {},
		success(res){
			console.log(res);
			if(res.code != 0){
				console.log(res);
				return;
			};
			
			// DOM操作
			let str = `<option value="">--请选择省--</option>`;
			res.data.forEach(item => {
				str += `<option value="${item.name}">${item.name}</option>`;
			})
			// 添加到页面
			oProvinceDom.innerHTML = str;
			
			oProvinceDom.onchange = function(){
				nowProvince = this.value;
				// 调用城市数据
				getCity(this.value, oCityDom, '--请选择市--');
			}
			
		}
	});
};
// 请求城市
function getCity(province, dom, strCity){
	lb.ajax({
		url: BASE_URL + '/api_country',
		data: {province},
		success(res){
			console.log(res);
			if(res.code != 0){
				console.log(res);
				return;
			};
			
			// 上海市-北京市等没有市 用市辖区代替
			let datas = res.data.area || res.data;
			// DOM
			let str = '<option value="">'+strCity+'</option>';
			datas.forEach(item => {
				str += `<option value="${item.name}">${item.name}</option>`;
			});
			// 添加到页面
			dom.innerHTML = str;
			
			dom.onchange = function(){
				nowCity = this.value;
				// 调用区数据
				getTown(nowProvince, nowCity, oTownDom, '--请选择区--');
			}
		}
	});
};

// 请求区
function getTown(province, city, dom, strTown){
	lb.ajax({
		url: BASE_URL + '/api_country',
		data: {province, city},
		success(res){
			console.log(res);
			if(res.code != 0){
				console.log(res);
				return;
			};
			
			//DOM
			let str = '<option value="">'+strTown+'</option>';
			let dataTown = res.data.area || res.data;
			dataTown.forEach(item => {
				str += `<option value="${item.name}">${item.name}</option>`;
			});
			// 添加到页面
			dom.innerHTML = str;
			dom.onchange = function(){
				nowTown = this.value;
			}
		}
		
	});
};

// 点击结算
let oSettleBtn = document.querySelector('.settle-btn');
let oSettleWay = document.querySelector('.settle-status');

oSettleWay.onchange = function(){
	// console.log(this.checked);
	settleStatus = this.checked;
};

	oSettleBtn.onclick = function(){
		
		if( !addressStatus){
			alert('未选中地址，请选择');
			return;
		}
		
		if( !settleStatus ){
			alert('支付方式未勾选，请勾选');
			return;
		};
		
		// 验证有没有选中地址
		// 验证有没有商品
		// 获取总价
		let priceAll = 0;
		lb.ajax({
			method: 'post',
			url: BASE_URL + '/api_settlement',
			data: {
				status : 'getsettlement',
				userId : localStorage.getItem('token'),
			},
			success(res){
				// console.log(res);
				if(res.code != 0){
					console.log(res);
					return;
				}
				res.data.forEach(item => {
					priceAll += item.price*item.goods_number;
				});
				// console.log(priceAll);
				
				// 请求支付地址
				lb.ajax({
					method: 'post',
					url: BASE_URL + '/api_payment',
					data: {
						userId: localStorage.getItem('token'),
						orderId: new Date().getTime(),
						returnUrl: 'http://127.0.0.1:8848/project/lc-2-pc/order.html',
						totalAmount: priceAll,
						subject: '订单',
						body: '订单详情'
					},
					success(res){
						console.log(res);
						if(res.code != 0){
							console.log(res);
							return;
						};
						// 获取支付地址成功
						location.href = res.data;
					}
				})
			}
			
		});
		
	};
